function f1 = makeLatexTableCont(table,options)
% ===========================================================================
% Function to create latex table from given matrix and row/column headers
%
% [Input]:
% table.dataMat: matrix of data
% table.rowLabels:  cell array of row title
% table.colLabels:  cell array of column title(on the top); 
% table.corner:  string, upper left corner of the graph
% table.tableHeader: string of Title name printed on the top of table
% 
% [Options]: (which are indeed optional)
% options.printPDF    : logical, 1 to print PDF
% options.fileName    : file name to write
% options.outPath     : location of directory for output
% options.orientation : orientation of table, 'portrait' or 'landscape'
% options.open        : logical, 1 to open a new file and begin writing
% options.append      : logical, 1 to append to existing file
% options.close       : logical, 1 to close out file and potentially print
%
% [Output]: 
% f1 returns the FID
% Alaways a TeX file contains the LaTeX commands for creating the table
% if options.printPDF, a PDF version of a table
% ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% This setup makes it easy for user to import this table to his main LaTeX
% article. He/She can do so simply by using the following command: 
% \input(table1.tex)
%
% ===============================================================================
%  RA: Xi Luo
%  Date Created: 05/12/2011
%  RA: Matt Olson
%  Date Modified: 1/3/2012

cucd=cd;

%% 1. Check inputs and set missing ones to default
if ~isfield(table,'corner')
    table.corner ='';
end
if ~isfield(table,'tableHeader')
    table.tableHeader = '';
end
if nargin < 2
    options = [];
end
if ~isfield(options,'outPath')
    options.outPath = cucd;
end
if ~isfield(options,'fileName')
    options.fileName ='table';
end
if ~isfield(options,'open')
    options.open = true;
end
if ~isfield(options,'append')
    options.append = false;
end
if ~isfield(options,'close')
    options.close = true;
end
if ~isfield(options,'orientation')
    options.orientation = 'portrait';
end
if ~isfield(options,'printPDF')
    options.printPDF = true;
end
if options.open && options.append
    error('Must choose to either open or append, not both!')
end
if ~isfield(table,'rowLabels')
    table.rowLabels = strcat('Row ', num2cprec(1:size(table.dataMat,1)));
end
if ~isfield(table,'colLabels')
    table.colLabels = strcat('Col ', num2cprec(1:size(table.dataMat,2)));
end
if isnumeric(table.dataMat); 
    isnum = 1; 
elseif iscell(table.dataMat); 
    isnum = 0; 
else
    error('datamat has either to be numeric or a cellarray')
end 
%% 2. Extract data
datamat = table.dataMat;
rowtit  = table.rowLabels;
coltit  = table.colLabels;
corner  = table.corner;
tablename = table.tableHeader;
fname = options.fileName;
outputpath = options.outPath;

[nrow, ncol] = size(datamat);

%% Begin Writing TeX Code to File
stylestr =  '{|l ||';
for ii = 1:ncol
    stylestr = [stylestr, 'c |' ];
end
stylestr =  [stylestr, '}'];

% If writing initial file, provide this preamble
if options.open 
    f1=fopen([fname,'.tex'],'w');
    if options.printPDF
        fprintf(f1, ['\\documentclass[',options.orientation, ', 12pt]{report} \n']);
        fprintf(f1, '\\usepackage{rotating} \n');
        fprintf(f1, '\\usepackage{longtable} \n');
        fprintf(f1, '\\usepackage{graphicx}  \n');
        fprintf(f1, '\\setlength{\\oddsidemargin}{-0.25in} \n');
        fprintf(f1, '\\begin{document} \n');
    end
end

% If appending to existing file, choose that option when opening
if options.append
    f1=fopen([fname,'.tex'],'a');
end

% If table is not empty, write it to file
if ~isempty(datamat)
    fprintf(f1, '\\begin{center} \n');
    fprintf(f1, ['\\begin{longtable}', stylestr, ' \n']);
    fprintf(f1, ['\\hline \n']);
    fprintf(f1, ['\\multicolumn{', num2str(ncol+1), '}{|c|}{', char(tablename),'} \\\\ \n']);
    fprintf(f1, ['\\hline \n']);
    for jj = 1:nrow+1 % row by row
        if jj == 1; % taking care of first row(fill in column title)
            rowstring = char(corner);
            for kk = 1:ncol;
                rowstring = [rowstring, '&', char(coltit{kk})];
            end
        elseif jj > 1;
            rowstring = rowtit{jj-1};
            for kk = 1:ncol % column by column
                if isnum
                    rowstring =  [rowstring, '&', num2str(datamat(jj-1, kk), '%3.2f')];
                else
                    rowstring =  [rowstring, '&', datamat{jj-1, kk}];
                end
            end
        end
        fprintf(f1, [rowstring, '\\\\ \\hline \n']);
    end

    fprintf(f1, '\\end{longtable} \n');
    fprintf(f1, '\\end{center} \n');

    % If we are not closing the file, add a pagebreak 
    if ~options.close
        fprintf(f1,'\\pagebreak \n');
    end
end
%% Procdures to Close File
if options.close
    
    if options.printPDF
        fprintf(f1, '\\end{document} \n');
    end
    fclose(f1);
    cd(cucd); 
    
    if options.printPDF==true
        if ~isunix
            fname_system = fname(isspace(fname)==0); 
        else
            fname_system = fname; 
        end
    
        if ~isunix
            [status,result] = system(['pdflatex ',  [fname_system,'.tex'], ' -quiet']);
        else
            [status,result] = system(['pdflatex "', [fname_system,'.tex'], '" -quiet']);
        end
        if ~status
            disp('Could not create PDF') 
            disp(result); 
        end        
        delete([fname,'.aux'], [fname,'.log'])
    end

    if strcmp(outputpath,cucd)==0
        % Copy the Latex File
        [success_tex,message_tex]=copyfile([fname,'.tex'],outputpath);
        if success_tex==0
            warning('Could not copy TEX file');
            disp(message_tex);
        else
            delete([fname,'.aux'], [fname,'.log'],[fname,'.tex'])
        end
        
        if options.printPDF
            if status==0 
                [success_pdf,message_pdf]=copyfile([fname_system,'.pdf'],outputpath);
                if success_pdf==0
                    warning('Could not copy pdf file');
                    disp(message_pdf);
                else
                    delete([fname_system,'.pdf'])
                end
            end 
        end
    end
end

end